package com.wmx.reddoor.jpa.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.stat.DruidStatManagerFacade;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * druid 数据源监控信息
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2022/3/15 14:44
 */
@RestController
public class DruidController {

    /**
     * Spring Boot 默认已经配置好了数据源，程序员可以直接 DI 注入然后使用即可
     */
    @Resource
    private DataSource dataSource;

    /**
     * 获取 druid 数据监控信息。
     * 其中统计了所有数据源的所有详细信息。
     * http://127.0.0.1:8080/myDruid/stat
     * <p>
     * 返回值如：\src\main\resources\DruidStatManagerFacade 获取 druid 数据监控信息.json
     *
     * @return
     */
    @GetMapping("myDruid/stat")
    public List<Map<String, Object>> druidStat() {
        List<Map<String, Object>> statDataList = DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
        return statDataList;
    }

    /**
     * 使用 DruidDataSource API 获取具体数据源的指定的监控信息
     * http://127.0.0.1:8080/myDruid/druidDataSource
     *
     * @return
     */
    @GetMapping("myDruid/druidDataSource")
    public Map<String, Object> druidDataSource() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("class", dataSource.getClass());
        if (dataSource instanceof DruidDataSource) {
            DruidDataSource druidDataSource = (DruidDataSource) dataSource;
            dataMap.put("version", druidDataSource.getVersion());
            dataMap.put("name", druidDataSource.getName());
            dataMap.put("initialSize", druidDataSource.getInitialSize());
            dataMap.put("maxActive", druidDataSource.getMaxActive());
            dataMap.put("minIdle", druidDataSource.getMinIdle());
            dataMap.put("activeCount", druidDataSource.getActiveCount());
            dataMap.put("activePeak", druidDataSource.getActivePeak());
            dataMap.put("activePeakTime", druidDataSource.getActivePeakTime());
            dataMap.put("poolingCount", druidDataSource.getPoolingCount());
            dataMap.put("poolingPeak", druidDataSource.getPoolingPeak());
            dataMap.put("poolingPeakTime", druidDataSource.getPoolingPeakTime());
        }

        /**返回值如：
         * {
         * 	"activeCount": 0,
         * 	"poolingCount": 10,
         * 	"minIdle": 10,
         * 	"activePeakTime": "2022-11-06T07:27:37.767+0000",
         * 	"poolingPeak": 10,
         * 	"initialSize": 10,
         * 	"poolingPeakTime": "2022-11-06T07:27:37.544+0000",
         * 	"activePeak": 1,
         * 	"name": "druid-db1",
         * 	"class": "com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceWrapper",
         * 	"version": "1.2.8",
         * 	"maxActive": 200
         * }
         */
        return dataMap;
    }


}
